package com.bolt.admin.module.sys.service;

import com.bolt.admin.module.email.service.EmailService;
import com.bolt.admin.properties.LoginProperties;
import com.bolt.common.io.resource.ResourceMode;
import com.bolt.common.utils.RandomUtil;
import com.bolt.convention.exception.ServiceException;
import com.bolt.support.cache.redis.RedisManager;
import com.bolt.support.freemarker.FreeMarkerEngine;
import com.bolt.support.freemarker.Template;
import com.bolt.support.freemarker.TemplateConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class VerifyService {

    @Autowired
    private EmailService emailService;

    @Autowired
    private RedisManager redisManager;

    @Autowired
    private LoginProperties loginProperties;



    public void sendEmailCode(String email, String key) {
        try {
            String redisKey = key + email;
            FreeMarkerEngine engine = new FreeMarkerEngine(new TemplateConfig("email_templates", ResourceMode.CLASSPATH));
            Template template = engine.getTemplate("emailCode.ftl");
            String oldCode = redisManager.get(redisKey);
            Map <String, Object> data = new HashMap <>(1);
            if (oldCode == null) {
                String code = RandomUtil.randomNumbers(6);
                redisManager.cache(redisKey, code, loginProperties.getCaptchaCode().getExpiration(), TimeUnit.MINUTES);
                data.put("code", code);
                String context = template.render(data);
                emailService.send(email, "邮箱验证码", context);
            } else {
                data.put("code", oldCode);
                String context = template.render(data);
                emailService.send(email, "邮箱验证码", context);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }


    public void validated(String key, String code) {
        String value = redisManager.get(key);
        if (value == null || !value.equals(code)) {
            throw new ServiceException("无效验证码");
        } else {
            redisManager.del(key);
        }
    }
}

 